package com.css.zfzx.sjcj.modules.qhdatatemplate.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.modules.qhdatatemplate.repository.QhDataTemplateNativeRepository;
import com.css.zfzx.sjcj.modules.qhdatatemplate.repository.QhDataTemplateRepository;
import com.css.zfzx.sjcj.modules.qhdatatemplate.repository.entity.QhDataTemplateEntity;
import com.css.zfzx.sjcj.modules.qhdatatemplate.service.QhDataTemplateService;
import com.css.zfzx.sjcj.modules.qhdatatemplate.viewobjects.QhDataTemplateQueryParams;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author tao
 * @date 2020-11-19
 */
@Slf4j
@Service
@PropertySource(value = "classpath:platform-config.yml")
public class QhDataTemplateServiceImpl implements QhDataTemplateService {

    @Value("${file-upload.attachment-directory.config.defaultDirectory.fileDirectory}")
    private String localPath;

	@Autowired
    private QhDataTemplateRepository qhDataTemplateRepository;
    @Autowired
    private QhDataTemplateNativeRepository qhDataTemplateNativeRepository;

    @Override
    public JSONObject queryQhDataTemplates(QhDataTemplateQueryParams queryParams, int curPage, int pageSize) {
        Page<QhDataTemplateEntity> qhDataTemplatePage = this.qhDataTemplateNativeRepository.queryQhDataTemplates(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhDataTemplatePage);
        return jsonObject;
    }


    @Override
    public QhDataTemplateEntity getQhDataTemplate(String id) {
        QhDataTemplateEntity qhDataTemplate = this.qhDataTemplateRepository.findById(id).orElse(null);
         return qhDataTemplate;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDataTemplateEntity saveQhDataTemplate(QhDataTemplateEntity qhDataTemplate) {
        String uuid = UUIDGenerator.getUUID();
        qhDataTemplate.setId(uuid);
        qhDataTemplate.setCreateUser(PlatformSessionUtils.getUserId());
        qhDataTemplate.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhDataTemplate.setIsValid("1");
        this.qhDataTemplateRepository.save(qhDataTemplate);
        return qhDataTemplate;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhDataTemplateEntity updateQhDataTemplate(QhDataTemplateEntity qhDataTemplate) {
        qhDataTemplate.setUpdateUser(PlatformSessionUtils.getUserId());
        qhDataTemplate.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhDataTemplateRepository.save(qhDataTemplate);
        return qhDataTemplate;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhDataTemplates(List<String> ids) {
        List<QhDataTemplateEntity> qhDataTemplateList = this.qhDataTemplateRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhDataTemplateList) && qhDataTemplateList.size() > 0) {
            for(QhDataTemplateEntity qhDataTemplate : qhDataTemplateList) {
//                this.qhDataTemplateRepository.delete(qhDataTemplate);
                qhDataTemplate.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDataTemplate.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDataTemplate.setIsValid("0");
                this.qhDataTemplateRepository.save(qhDataTemplate);
            }
        }
    }

    private void addOrUpdateQhDataTemplates(String name) {
        QhDataTemplateQueryParams params = new QhDataTemplateQueryParams();
        params.setTemplateName(name);

        Page<QhDataTemplateEntity> qhDataTemplatePage = this.qhDataTemplateNativeRepository.queryQhDataTemplates(params, 1, 10);

        QhDataTemplateEntity qhDataTemplateEntity = new QhDataTemplateEntity();
        qhDataTemplateEntity.setTemplateName(name);

        //update add
        if(qhDataTemplatePage.getContent().size() > 0) {
            qhDataTemplateEntity = qhDataTemplatePage.getContent().get(0);
            this.updateQhDataTemplate(qhDataTemplateEntity);
        } else {
            this.saveQhDataTemplate(qhDataTemplateEntity);
        }
    }

    @Override
    public void upload(MultipartFile file) {
        try {
            String path = localPath + "/excel";//上传的路径
            File dir = new File(path);
            if (!dir.exists()) {
                //路径不存在就创建路径
                dir.mkdir();
            }
            String fileName = file.getOriginalFilename();
            File file1 = new File(path, fileName);
            file.transferTo(file1);

            addOrUpdateQhDataTemplates(fileName.substring(0,fileName.lastIndexOf('.')));
        } catch (IOException e) {
            //throw new Exception(e.getMessage());
            log.error(e.getMessage());
        }
    }

    @Override
    public void download(String name, HttpServletResponse response) {
        try {
            String path = localPath + "/excel";//文件的下载地址
            String fullName = name + ".xls";
            //设置响应头
            response.reset();//设置页面不缓存
            response.setCharacterEncoding("UTF-8");//字符集编码
            response.setContentType("multipart/form-data");//二进制传输文件
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fullName, "UTF-8"));//设置响应头
            File file = new File(path, fullName);
            //输入流
            FileInputStream inputStream = new FileInputStream(file);
            //输出流
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] bytes = new byte[10240000];
            int index = 0;
            while ((index = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {

        }
    }

}
